# -*- coding: UTF-8 -*-
import sys

from highcharts import Highchart, Highstock

import pandas as pd
import numpy as np
from config import config
import matplotlib.pyplot as plt


def init(blogname):
    df = pd.read_excel(open(config.get_excel_name_s(blogname, 'a'), 'rb'), sheet_name='sheet1',
                       header=None,
                       names=['match', 'pick', 'odd', 'stake', 'pick_type', 'profit', 'result', 'sport', 'category',
                              'kickoff', 'kickoff_time'])
    pd.options.display.float_format = '{:,.1f}'.format
    pd.set_option('display.height', 1000)
    pd.set_option('display.max_rows', 500)
    pd.set_option('display.max_columns', 700)
    pd.set_option('display.width', 1000)

    return df


def filter(df, query_array):
    filtered_df = df
    if query_array:
        for item in query_array:
            filtered_df = filtered_df.query(item)
    return filtered_df


def show_yield(cumsum_df):
    # print '========  show yield     ========'
    cumsum_df['yield'] = cumsum_df['profit'] / cumsum_df['stake'] * 100
    return cumsum_df


def print_day_duration(df, days_count):
    print('DAY:   %s ==> %s     (days:%s ,count:%d)' %
          (df['kickoff'].min(), df['kickoff'].max(), days_count, len(df['kickoff'])))


def analyse(blog_name, query_array):
    df = init(blog_name)
    df = filter(df, query_array)

    pivot_table = pd.pivot_table(df, values=['profit', 'stake'], index=['kickoff'],
                                 aggfunc={'profit': 'sum', 'stake': 'sum'}, fill_value=0, margins=False)
    # print pivot_table.tail(15)
    cumsum_df = pivot_table.cumsum()
    print_day_duration(df, len(cumsum_df['stake']))

    # df.set_index('kickoff', inplace=True)
    # df.sort(inplace=True)

    pivot_table = pd.pivot_table(df, values=['profit', 'stake'], index=['kickoff'],
                                 aggfunc={sum}, fill_value=0, margins=False)
    cumsum_df = show_yield(pivot_table.cumsum())
    profit_list = []
    stake_list = []
    yield_list = []
    date_list = []
    for index, row in cumsum_df.iterrows():
        profit_list.append(
            round(row[0], 0),  # the date
        )
        stake_list.append(
            row[1]
        )
        yield_list.append(
            round(row[2], 0)
        )
        date_list.append(
            index
        )
    show_as_hightchart(blog_name, profit_list, stake_list, yield_list, date_list)


def show_as_hightchart(blog_name, profit_list, stake_list, yield_list, date_list):
    H = Highchart(height=500)
    options = {
        'chart': {
            'zoomType': 'xy'
        },
        'title': {
            'text': blog_name
        },
        'subtitle': {
            'text': 't'
        },
        'xAxis': [{
            'categories': date_list,
            'crosshair': True
        }],
        'yAxis': [{
            'gridLineWidth': 0,
            'title': {
                'text': config.STAKE,
                'style': {
                    'color': 'Highcharts.getOptions().colors[0]'
                }
            },
            'labels': {
                'format': '{value}' + config.STAKE_ICON,
                'style': {
                    'color': 'Highcharts.getOptions().colors[0]'
                }
            }
        }, {
            'labels': {
                'format': '{value} ' + config.PROFIT_ICON,
                'style': {
                    'color': 'Highcharts.getOptions().colors[1]'
                }
            },
            'title': {
                'text': config.PROFIT,
                'style': {
                    'color': 'Highcharts.getOptions().colors[1]'
                }
            },
        }, {
            'gridLineWidth': 0,
            'title': {
                'text': config.YIELD,
                'style': {
                    'color': 'Highcharts.getOptions().colors[2]'
                }
            },
            'labels': {
                'format': '{value} ' + config.YIELD_ICON,
                'style': {
                    'color': 'Highcharts.getOptions().colors[2]'
                }
            },
            'opposite': True
        }],
        'tooltip': {
            'shared': True,

        },
        'legend': {
            'layout': 'vertical',
            'align': 'left',
            'x': 180,
            'verticalAlign': 'top',
            'y': 55,
            'floating': True,
            'backgroundColor': "(Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'"
        },
    }
    H.set_dict_options(options)

    H.add_data_set(stake_list, 'spline', config.STAKE, yAxis=0, marker={
        'enabled': False
    }, tooltip={
        'valueSuffix': config.STAKE_ICON
    })

    H.add_data_set(profit_list, 'spline', config.PROFIT, yAxis=1, tooltip={
        'valueSuffix': config.PROFIT_ICON
    })
    H.add_data_set(yield_list, 'spline', config.YIELD, yAxis=2, tooltip={
        'valueSuffix': config.YIELD_ICON
    })

    H.save_file(filename='caonmma')


blog_name = 'tennismajgy'
query_array = []
query_array.append('profit/stake<5')

analyse(blog_name, query_array)
